package com.cudex.negocio.daos;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;

import com.cudex.negocio.beans.Clientes;

@Stateless
public class ClientesDAO implements IClientesDAO {

	private static final long serialVersionUID = 1736912231844133813L;

	private static final Logger log = Logger.getLogger(ClientesDAO.class
			.getName());

	@PersistenceContext(unitName = "JPA_UNIT_CUDEX")
	EntityManager em;

	@Override
	
	public Boolean altaCliente(Clientes c) throws Exception {
		Boolean result = false;
		log.info("guardando");
		try {
			em.persist(c);
			result = true;
		} catch (ConstraintViolationException e) {

			// log.error("salvarTipo : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("salvarTipo : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return result;
	}

	@Override
	public Clientes modificarCliente(Clientes c) throws Exception {
		Clientes objTmp = null;
		try {
			objTmp = em.merge(c);
			em.flush();

		} catch (ConstraintViolationException e) {
			// log.error("modificarTipo : ConstraintViolationException");
			throw e;
		} catch (PersistenceException e) {
			// log.error("modificarTipo : PersistenceException");
			throw e;
		} catch (Exception e) {
			throw e;
		}
		return objTmp;
	}

	@Override
	public List<Clientes> buscarClienteNombre(String nombre) throws Exception {
		try {
			// Clientes objTmp = (Clientes) em
			List<Clientes> objTmp = (List<Clientes>) em
					.createNamedQuery("buscarClientePorNombre", Clientes.class)
					.setParameter("nom", nombre).getResultList();
			return objTmp;
		} catch (Exception e) {
			log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
	}

	@Override
	public Clientes buscarCliente(Clientes c) throws Exception {
		try {
			Clientes objTmp = (Clientes) em
					.createNamedQuery("buscarCliente", Clientes.class)
					.setParameter("Cliente", c).getSingleResult();

			return objTmp;
		} catch (Exception e) {
			log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Clientes> buscarClientes() throws Exception {
		List<Clientes> result = null;
		try {
			result = (List<Clientes>) em.createNamedQuery("buscarClientes")
					.getResultList();
			log.info("Count Clientes : " + result.size());
		} catch (Exception e) {
			log.error(e.getCause());
			// e.printStackTrace();
			throw e;
		}
		return result;
	}

}
